<script>
  import common, { ComponentName } from '../common.js'
  import mxMarker from '../marker/index.vue'

  export default {
    components: { mxMarker },
    props: {
      name: {},
      show: {},
      layer: {},
      map: {},
      options: {},
      sources: {},
      zoom: {},
      category: {},
      activeLayerList: {}
    },
    computed: {
      currentVisible() {
        return this.show && this.currentShow
      },
      currentShow() {
        if (!this.layer.zoom) return true
        let [start, end] = this.layer.zoom
        return this.zoom >= Number(start) && this.zoom <= Number(end)
      },
      currentSources() {
        let [source = this.name] = this.layer.source || []
        if (!source) return []
        return this.sources[source] || []
      }
    },
    methods: {
      startSubscribe() {
        let [source = this.name] = this.layer.source || []
        let { collectionName, liveCollectionName, liveEvents, liveOptions, liveMatch } = this.options.sources[source]
        if (!liveEvents) return
        let table = liveCollectionName || collectionName
        let options = typeof liveOptions === 'function' ? liveOptions.call(this, this.currentSources) : liveOptions
        this.subscribe = common.liveQuery(table, options)
        liveEvents.forEach(item => {
          this.subscribe.on(item, (object) => {
            if (liveMatch) {
              object = liveMatch.call(this, object, this.currentSources)
            } else {
              object = { ...object, ...object.attributes }
            }
            this.$emit('liveQuery', { name: this.name, event: item, object: object })
          })
        })
      },
      endSubscribe() {
        if (!this.subscribe) return
        this.subscribe.unsubscribe()
      },
      judgeSubscribe() {
        this.currentVisible ? this.startSubscribe() : this.endSubscribe()
      }
    },
    created() {
      const options = { name: this.name, layer: this.layer, complete: this.judgeSubscribe }
      this.$emit('create', options)
    },
    activated() {
      this.judgeSubscribe()
    },
    deactivated() {
      this.judgeSubscribe()
    },
    destroyed() {
      this.$emit('destroy')
      this.judgeSubscribe()
    },
    watch: {
      currentVisible() {
        this.judgeSubscribe()
      }
    }
  }
</script>
